require 'date2'

class InController < ApplicationController

  before_filter :verify_session,:gettag_counts
  def step1
  end
  
  def step2
    book = Book.find(:first,:conditions => ["lt_code = ?",params[:book][:lt_code]])
    if book != nil
      @out_record = OutRecord.find(:first,:conditions => ["book_id =?",book.id])
    end
    
    if @out_record == nil
      flash[:error] = "没有这本书的借书记录!"
      else
      @reader = @out_record.reader
      @book = @out_record.book
    end
  end
  
  def showNeedcheckInRecords
    @outrecords = OutRecord.find_by_sql('select out_records.* from out_records,books where out_records.book_id=books.id and (books.book_status_id=5)')
    render :layout=>false
  end
  
  def inSubmit
    book = Book.find(params[:id])
    book.book_status_id = 1
    out_record = book.out_record
    histry_rcd = generateHistory_rcd(out_record)
    begin
      OutRecord.transaction do
        out_record.destroy
        book.update
        histry_rcd.save!
#       send mail here
       deliver_email(histry_rcd,out_record)
       flash[:notice] = "还书操作成功!"
      end
    rescue
        flash[:notice] = "还书操作失败!"
    end
    redirect_to :controller =>'out', :action => 'showNeedcheckRecords'
  end
  
  def returnback
    out_record = OutRecord.find(params[:id])
    book = out_record.book
    book.book_status_id = 1
    histry_rcd = generateHistory_rcd(out_record)
    begin
      OutRecord.transaction do
        out_record.destroy
        book.update
        histry_rcd.save!
        deliver_email(histry_rcd,out_record)
        flash[:notice]="还书操作成功!"
        redirect_to :action=>'list' ,:controller => 'out'
      end
    rescue
        flash[:notice]="还书操作失败!"
        redirect_to :action=>'list' ,:controller => 'out'
    end
  end
  
  def self_return
    out_record = OutRecord.find(params[:id])
    book = out_record.book
    book.book_status_id = 5
#    histry_rcd = generateHistory_rcd(out_record)
    begin
      OutRecord.transaction do
        book.update
        email = BookMailer.create_newInRecord(out_record)
        BookMailer.deliver(email)
        flash[:notice]="还书请求已经发送到管理员,请携带要归还的图书到管理员那里确认!"
        redirect_to :action=>'search_myOut' ,:controller => 'out'
      end
    rescue
        flash[:notice]="还书操作失败!"
        redirect_to :action=>'search_myOut' ,:controller => 'out'
    end
  end
  
  private 
#  根据用户的借书记录(out_record),生成相应的历史记录
  def generateHistory_rcd(out_record)
    histry_rcd = HistryRecord.new
    histry_rcd.reader_name = out_record.reader.reader_name
    histry_rcd.book_name = out_record.book.book_name
    histry_rcd.out_date = out_record.date
    histry_rcd.in_date = Date.today()
    histry_rcd.is_overtime = histry_rcd.in_date <=> out_record.return_date
    return histry_rcd
  end
  
  def deliver_email(histry_rcd,out_record)
     email = BookMailer.create_returnbook(histry_rcd,out_record)
     BookMailer.deliver(email)
  end
  
end
